package very.util.quartz
import java.util.Date

import akka.actor.{ActorRef, ActorSystem}
import com.joyrec.util.log.impl.slf4j.ClassSlf4jDebugLog
import org.quartz._
import org.quartz.impl.DirectSchedulerFactory
import org.quartz.simpl.{RAMJobStore, SimpleThreadPool}

class QuartzManager(system: ActorSystem) extends ClassSlf4jDebugLog {

  val threadPool = new SimpleThreadPool(2, 1)
  threadPool.setThreadNamePrefix("Quartz_")

  DirectSchedulerFactory.getInstance().createScheduler(threadPool, new RAMJobStore())
  val scheduler = DirectSchedulerFactory.getInstance().getScheduler
  scheduler.startDelayed(2)

  system.registerOnTermination({
    info("Quartz Shutdown")
    if (!scheduler.isShutdown) {
      scheduler.shutdown()
    }
  })

  def schedulerJob(jobDetail: JobDetail, trigger: Trigger): Date = {
    scheduler.scheduleJob(jobDetail, trigger)
  }

  def actorScheduler(name: String, cronExpression: String, receiver: ActorRef, message: AnyRef) = {
    info(s"quartz $name register")
    val job = JobBuilder
      .newJob(classOf[SimpleActorMessageJob])
      .withIdentity(s"${name}_job")
      .setJobData(SimpleActorMessageJob.jobData(receiver, message))
      .build()

    val trigger = TriggerBuilder
      .newTrigger()
      .withIdentity(s"${name}_trigger")
      .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
      .build()
    schedulerJob(job, trigger)
  }

}
